package org.budo.support.yaml.util;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
import java.util.Map.Entry;

import org.budo.support.lang.util.StringUtil;
import org.yaml.snakeyaml.Yaml;

/**
 * @author limingwei
 */
public class YamlUtil {
    /**
     * 将一个YML文件的内容 读取为键值对
     */
    public static Map<String, String> ymlToMap(InputStream inputStream) {
        Map<Object, Object> ymlMap = (Map<Object, Object>) new Yaml().load(inputStream);
        Map<String, String> ymlMapToRawMap = ymlMapToRawMap(null, ymlMap);
        return new TreeMap<String, String>(ymlMapToRawMap);
    }

    /**
     * 将yml的层级map转换为单层map
     */
    private static Map<String, String> ymlMapToRawMap(String prefix, Map<Object, Object> ymlMap) {
        Map<String, String> valueMap = new HashMap<String, String>();
        for (Entry<Object, Object> entry : ymlMap.entrySet()) {
            Object value = entry.getValue();
            String key = entry.getKey().toString();

            String prefixKey = StringUtil.isEmpty(prefix) ? key : prefix + "." + key;

            if (value instanceof Map) {
                Map<String, String> ymlToMap = ymlMapToRawMap(prefixKey, (Map) value);
                valueMap.putAll(ymlToMap);
            } else {
                valueMap.put(prefixKey, value.toString());
            }
        }
        return valueMap;
    }
}